package com.example.security.interceptor;

import com.example.security.annotation.RequirePermission;
import com.example.security.util.SecurityUtils;
import com.example.security.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Set;

@Component
@RequiredArgsConstructor
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequirePermission permission = handlerMethod.getMethodAnnotation(RequirePermission.class);
        
        if (permission == null) {
            return true;
        }

        String username = SecurityUtils.getCurrentUser().getUsername();
        Set<String> permissions = (Set<String>) redisTemplate.opsForValue()
            .get("permissions:" + username);
            
        if (permissions == null) {
            throw new AccessDeniedException("权限信息已失效");
        }

        boolean hasPermission = permissions.contains(permission.value());

        if (!hasPermission) {
            throw new AccessDeniedException("没有操作权限");
        }

        return true;
    }
} 